package com.h52mm.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class UpdateNote implements Watcher {

    private static ZooKeeper zooKeeper;
    public static void main(String[] args) throws IOException, InterruptedException {
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new UpdateNote());
        //不让main 函数停止
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            try {
                updateNodeSync();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    private void updateNodeSync() throws Exception {
        /*
        path:路径
        data:要修改的内容 byte[]
        version:为-1，表示对最新版本的数据进⾏修改
        zooKeeper.setData(path, data,version);
        */
        byte[] data = zooKeeper.getData("/test_persistent", false, null);
        System.out.println("修改前的值:"+new String(data));
       //修改 stat:状态信息对象 -1:最新版本
        Stat stat = zooKeeper.setData("/test_persistent", "修改内容45678".getBytes(), -1);
        byte[] data2 = zooKeeper.getData("/test_persistent", false, null);
        System.out.println("修改后的值:"+new String(data2, StandardCharsets.UTF_8));
    }

}
